/***********************************************************************************************************************************
 * Name:	Build_MERGE.sql
 * Author:	Frank Figearo (frank.figearo@us.bbaaviation.com|frank@sqlnerd.me)
 * Summary:	
 */
SET IMPLICIT_TRANSACTIONS OFF; IF 0 < @@TRANCOUNT ROLLBACK;
GO
DECLARE
	@TableName	SYSNAME		= N'',
	@Columns	NVARCHAR(MAX);
DECLARE @line TABLE (linenumber INT NOT Null IDENTITY(1,1), linetext NVARCHAR(MAX));

-- MATCHED
INSERT INTO @line (linetext)
SELECT N'		' + QUOTENAME(name) + N'	= src.' + QUOTENAME(name) + N','
  FROM sys.columns
  WHERE [object_id] = OBJECT_ID(@TableName)
  ORDER BY column_id;

-- NOT MATCHED - INSERT
INSERT INTO @line (linetext) VALUES (N'  WHEN NOT MATCHED THEN');

SET @Columns= N'	INSERT (';
SELECT @Columns+= SPACE(4)+QUOTENAME(name) + N', '
  FROM sys.columns
  WHERE [object_id] = OBJECT_ID(@TableName)
  ORDER BY column_id;
SET @Columns+= N')';
INSERT INTO @line (linetext) VALUES (REPLACE(@Columns, N'], )', N'])'))

SET @Columns= N'	VALUES (';
SELECT @Columns+= N'src.'+QUOTENAME(name) + N', '
  FROM sys.columns
  WHERE [object_id] = OBJECT_ID(@TableName)
  ORDER BY column_id;
SET @Columns+= N');';
INSERT INTO @line (linetext) VALUES (REPLACE(@Columns, N'], )', N'])'))

SELECT * FROM @line
GO